<?php


namespace App\Service;

/**
 * 机器翻译2.0(niutrans) WebAPI 接口调用示例
 * 运行前：请先填写Appid、APIKey、APISecret
 *
 * 1.接口文档（必看）：https://www.xfyun.cn/doc/nlp/niutrans/API.html
 * 2.错误码链接：https://www.xfyun.cn/document/error-code （错误码code为5位数字）
 * 3.个性化翻译术语自定义：
 * ***登陆开放平台 https://www.xfyun.cn/
 * ***在控制台--机器翻译(niutrans)--自定义翻译处
 * ***上传自定义翻译文件（打开上传或更新窗口，可下载示例文件）
 * @author iflytek
 *
 * $a = new ots_test();
 * $a->xfyun();
 *
 */
class TranslateBaidu
{


    const API_KEY    = "me9Laf0wNrhHzOX9WvFUkOtw";
    const SECRET_KEY = "7hNklDxhn1T9PdS61yIN6vnB5AolOqBv";

    // 执行翻译
    public function run($text, $from = "zh", $to = 'en')
    {
        $param = ['from' => $from, 'to' => $to, 'q' => $text];
        $curl  = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL            => "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token={$this->getAccessToken()}",
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_CUSTOMREQUEST  => 'POST',
            CURLOPT_POSTFIELDS     => json_encode($param, JSON_UNESCAPED_UNICODE),
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'Accept: application/json',],
        ));
        $response = curl_exec($curl);
        curl_close($curl);

        return $response;
    }

    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    private function getAccessToken()
    {

        $postData = array(
            'grant_type'    => 'client_credentials',
            'client_id'     => self::API_KEY,
            'client_secret' => self::SECRET_KEY,
        );

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL            => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST  => 'POST',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS     => http_build_query($postData),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);

        return $rtn->access_token;
    }
}

